import type {VectorView} from "../interfaces/render-object";
import {drawImageWithAspectRatio} from "@/canvasCut/utils/ImgUtil";
import { cloneDeep, uniqueId } from "lodash";

export interface BaseNodeParams {
    x?: number;
    y?: number;
    width: number;
    height: number;
    angle?: number;
    scale?: number;
    type: 'image' | 'text';

    // 图层zIndex
    zIndex?: number;
    // 是否选中
    isSelected?: boolean;

    // 是否锁定 图层
    isLock?: boolean;

    context?: CanvasRenderingContext2D;

    _canvas: any;
    flipX: 1 | -1;
    flipY: 1 | -1;
}

export  class BaseNode {
    __id__:number;
    _type: 'image' | 'text' | 'btn';
    width: number = 0;
    height: number = 0;
    x: number = 0;
    y: number = 0;
    scale: number = 1;
    /**
     * 原始数据大小
     */
    originalWidth: number = 0;
    originalHeight: number = 0;
    zIndex: number = 1;

    isSelected: boolean = false;
    isLock: boolean = false;

    _context: CanvasRenderingContext2D;

    canvas: any;

    // 旋转角度
     rotation: number = 0;
    // 是否拖拽对象
     isDragging = false;
    //
     lastX = 0;
    //
     lastY = 0;

    // 双指操作
    startDistance = 0;
    startAngle = 0;

    show: boolean = true;
    centerXY: [number, number] = [0,0]

    private _box = {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        rotation: 0
    };

    // 水平翻转
    flipX: 1 | -1 = 1;
    // 垂直翻转
    flipY: 1 | -1 = 1;

    // 左上 右上 右下 左下
    private _point: Array<{ x: number;
        y: number;
    }>;

    _canvasWidth: number;
    _canvasHeight: number;


    public _color: string;
    private _vectorView: VectorView;

    public _aiShirtCanvas: any;
    constructor(param: BaseNodeParams) {
        // // console.log('baseNode constructor', param)
        const {x, y, width, height, scale, type, zIndex, isSelected, isLock} = param;
        this.originalWidth = width;
        this.originalHeight = height;
        this._context = param.context;
        this.flipX =  param.flipX ?? 1;
        this.flipY =  param.flipY ?? 1;

        this.zIndex = zIndex || 1;
        this.isSelected = isSelected || false;
        this.isLock = isLock || false;
        this.x = Math.max(0, Math.floor(x));
        this.y = Math.max(0, Math.floor(y));
        this.scale = scale || 1;
        this._type = type;
        this.width = Math.floor(width);
        this.height = Math.floor(height);
        // this.width = ~~this.width;
        // this.height = ~~this.height;
        this.__id__ = uniqueId('node__')

        this._point = [
            {
                x: param.x,
                y: param.y
            },
            {
                x: param.x + this.width,
                y: param.y
            },
            {
                x: param.x + this.width,
                y: param.y + this.height
            },
            {
                x: param.x,
                y: param.y + this.height
            }
        ];
        this.centerXY = param.centerXY;
        this._box = {
            x: param.x,
            y: param.y,
            width,
            height,
            rotation: 0
        }
        this.canvas = param.canvas
        this._canvasWidth = param.canvasWidth;
        this._canvasHeight = param.canvasHeight;
    }

    setAIShirtCanvas(canvas) {
        this._aiShirtCanvas = canvas
    }

    updateBox({x, y, width, height}): void {
        this._box = {
            x,
            y,
            width,
            height,
            rotation: 0
        }
    }

    public getCopyNode() {
        const _this = cloneDeep(this);
        _this.__id__ = uniqueId('node__')
        return _this;
    }

    /**
     * 居中设置
     */
    resetLocation() {
        this.x = this.centerXY[0] - this.width / 2;
        this.y = this.centerXY[1]- this.height / 2;
        this.updateBox({x: this.x, y: this.y, width: this.width, height: this.height})
    }

    /**
     * 改变位置
     * @param type
     */
    moveXY(type) {
        let { x, y } = this;
        if (type === 'addY') {
            y = y + 1;
        } else if (type === 'subtractY') {
            y = y - 1;
        } else if (type === 'subtractX') {
            x = x - 1;
        } else if (type === 'addX') {
            x = x + 1;
        }
        this.x = x;
        this.y = y;
        this.updateBox({x: this.x, y: this.y, width: this.width, height: this.height})
    }

    /**
     * 改变旋转角度 水平垂直
     * @param type
     */
    changeFlip(type) {
        if (type === 'flipX') {
            this.flipX =  this.flipX === 1 ? -1 : 1;
        } else if (type === 'flipY') {
            this.flipY = this.flipY === 1 ? -1 : 1;
        }
    }


    /**
     * 图层 zIndex
     */
    layerUpdate(zIndex: number) {
        this.zIndex += zIndex;
    };

    private set_type(type: 'image' | 'text') {
        this._type = type;
    }


    /**
     * 解锁图层
     */
    updateLock(lock: boolean): void {
        this.isLock = lock;
    };


    // 放大/缩小对象
    scaleUpdate(type: 'up' | 'down') {
        const scale = type === 'up' ? 1.2 : 0.8;
        selectedObject.width *= 1.2;
        selectedObject.height *= 1.2;
    }

    // 触摸开始
    public touchStart(e: WechatMiniprogram.TouchEvent) {
        e.stopPropagation(); // 阻止事件冒泡
        // console.log('handleTouchStart', e)
        const touches = e.touches;

        if (touches.length === 1) {
            // 单指操作 - 开始拖动
            this.isDragging = true;
            this.lastX = touches[0].x;
            this.lastY = touches[0].y;
        } else if (touches.length === 2) {
            // fixme
            // // 双指操作 - 记录初始状态
            // this.isDragging = false;
            //
            // // 计算初始距离
            // const dx = touches[0].x - touches[1].x;
            // const dy = touches[0].y - touches[1].y;
            // this.startDistance = Math.sqrt(dx * dx + dy * dy);
            //
            // // 计算初始角度
            // this.startAngle = Math.atan2(dy, dx) * 180 / Math.PI;
        }
    }

    // 触摸移动
    public touchMove(e: WechatMiniprogram.TouchEvent) {
        // // console.error('handleTouchMove', e)
        e.stopPropagation(); // 阻止事件冒泡
        const touches = e.touches;

        if (touches.length === 1 && this.isDragging) {
            // // console.error('单指拖动')
            // 单指拖动
            const deltaX = touches[0].x - this.lastX;
            const deltaY = touches[0].y - this.lastY;

            this.x += deltaX;
            this.y += deltaY;

            this._box.x += deltaX;
            this._box.y += deltaY;

            this.lastX = touches[0].x;
            this.lastY = touches[0].y;
        } else if (touches.length === 2) {
            // fixme
            // // 双指操作
            // const dx = touches[0].x - touches[1].x;
            // const dy = touches[0].y - touches[1].y;
            //
            // // 计算当前距离
            // const distance = Math.sqrt(dx * dx + dy * dy);
            //
            // // 计算缩放比例
            // const scale = distance / this.startDistance;
            // this.scale *= scale;
            //
            // // 限制缩放范围
            // this.scale = Math.max(0.1, Math.min(5, this.scale));
            //
            // // 计算旋转角度
            // const angle = Math.atan2(dy, dx) * 180 / Math.PI;
            // const rotationDelta = angle - this.startAngle;
            // this.rotation += rotationDelta;
            //
            // // 更新初始状态
            // this.startDistance = distance;
            // this.startAngle = angle;
        }
    }

    // 触摸结束
    public touchEnd() {
        // e.stopPropagation(); // 阻止事件冒泡
        this.isDragging = false;
    }

    private _createImageNode(imgSrc) {
        return new Promise((resolve, reject) => {
            const image = this._canvas.createImage()
            image.onload = (res) => {
                resolve( {image})
            }
            image.src = imgSrc
        })
    }

    public _offScreenCanvas = null;
    public _offScreenCtx = null;


    /**
     * 创建一个离屏元素
     * @param width
     * @param height
     * @private
     */
    public getOffScreenCanvas() {
        const width = this.width;
        const height = this.height;
        // 创建离屏 2D canvas 实例
        const canvas = uni.createOffscreenCanvas({type: '2d', width , height })
        // 获取 context。注意这里必须要与创建时的 type 一致
        const context = canvas.getContext('2d')
        this._offScreenCanvas = canvas;
        this._offScreenCtx = context;
        return context;
    }

    /**
     * 截取内容区域
     */
    public getOffScreenCanvasImageMark() {
        // console.log('getOffScreenCanvasImageMark', this.x, this.y, this.width, this.height)
        // 确保坐标值为有效整数
        const x = this.x;
        const y = this.y;
        const width = Math.ceil(this.width);
        const height = Math.ceil(this.height);

        return this._offScreenCanvas.toDataURL('image/webp', 0.1); //( 'image/png', 0.1)
        // const imageData = this._offScreenCtx.getImageData(0, 0, width, height);
        // return imageData;
    }


    public async copy() {
       return cloneDeep(this);
    }

    public  exportData() {
        // console.log('paste', data)

        return {
            x: this.x,
            y: this.y,
            width: this.width,
            height: this.height,
            zIndex: this.zIndex,
            isLock: this.isLock,
            flipX: this.flipX,
            flipY: this.flipY,
            rotation: this.rotation,
            scale: this.scale,
            originalWidth: this.originalWidth,
            originalHeight: this.originalHeight,
            isSelected: this.isSelected,
            type: this._type,
            __id__: this.__id__,
            show: this.show,
            centerXY: this.centerXY,
            // canvasWidth: this._canvasWidth,
            // canvasHeight: this._canvasHeight
        }
    }
}
